/*!
 * New Launch.
 * Date: 2015/12/29.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
  "jquery",
  "pageInit",
  "formValidator",
  "formAjax",
  "notification",
  "select2",
  'materialPreview',
  'holder',
  'uploadFiles'
], function($, vamakerPage, formValidator, formAjax, VamOpMsg, select2, MaterialPreview, holder, UploadFiles) {
  $(function() {
    var 
      $adsSelectedList = $('#ads_selected_list'),
      $adsSizeList = $('#ads_size_list'),
      $adsFormatList = $('#ads_format_list'),
      $appType = $('.app-type'),
      adsToAppList = VAM.getVar('ADS_TO_APP_LIST'),
      appSizeAndFormatList = VAM.getVar('ADS_SIZE_FORMAT_LIST'),
      adsSizeListRender, adsFormatListRender;

    adsSizeListRender = function (data) {
      var
        sizeList = '',
        len = data.length;
      if (len !== 0) {
        for(var i = 0; i < len; i++) {
          if (i < 1) {
            sizeList += '<span class="list-item">' + data[i] + '</span>';
          } else {
            sizeList += '<span class="list-item">，' + data[i] + '</span>';
          }
        }

        $adsSizeList.html(sizeList);
      }
    };

    adsFormatListRender = function (data) {
      var
        formatList = '',
        len = data.length;
      if (len !== 0) {
        for(var i = 0; i < len; i++) {
          if (i < 1) {
            formatList += '<span class="list-item">' + data[i] + '</span>';
          } else {
            formatList += '<span class="list-item">，' + data[i] + '</span>';
          }
        }

        $adsFormatList.html(formatList);
      }
    };

    $adsSelectedList.select2({
      language: "zh-CN",
      placeholder: VAM.j('Select adspace name'),
      ajax: {
        data: function (params) {
          var $appTypeChecked = $appType.filter(':checked'),
            trafficArr = [];
          var query = {
            search: params.term,
            type: $appTypeChecked.val()
          };

          return query;
        },
        url: adsToAppList,
        dataType: 'json',
        delay: 1000,
        processResults: function (data) {
          return {
            results: data.items
          }
        },
        cache: true
      },
      minimumInputLength: 1,
    });

    $appType.on('change', function (evt) {
      $adsSelectedList.val(null).trigger('change');
    });

    $adsSelectedList.on('change', function (evt) {
      var
        $me = $(this),
        meVal = $me.val();
      // console.log($(this).val());
      $.ajax({
        url: appSizeAndFormatList,
        type: 'get',
        data: {
          app: meVal
        }
      })
      .done(function(data) {
        if (data.status === 'success') {
          adsSizeListRender(data.data.sizeList);
          adsFormatListRender(data.data.formatList);
        } else {
          VamOpMsg.messager(data);
        };
      })
      .fail(function() {
        console.log('error!');
      })
      .always(function() {
        console.log('change');
        $me.trigger('blur');
      });
    })
  });

  $(function() {
    var $dataFrm = $("#data-frm"),
      $submitBtn = $dataFrm.find('button[type="submit"]'),
      dataFieldRule,
      options,
      dataValidator;
    // console.log($dataFrm);
    dataFieldRule = {
      app_name: {
        rule: {
          required: {
            message: VAM.j("APP name cannot be empty")
          },
          maxlength: {
            param: 32,
            message: VAM.j("APP name for a maximum of 32 characters")
          }
        },
        messageContainer: "app_name_err"
      },
      ads_selected_list: {
        rule: {
          required: {
            message: VAM.j("Adspace list cannot be empty")
          }
        },
        messageContainer: 'ads_selected_list_err'
      },
      floor_price:{
        rule:{
          required:{
            message: VAM.j('Floor price cannot be empty')
          },
          floatnumber:{
            message: VAM.j('Input correct number')
          },
          validnum1: {
            param: $('#ceiling_price'),
            message: VAM.j('Please input the floor price')
          }
        },
        messageContainer:'floor_price_err'
      },
      ceiling_price:{
        rule:{
          required:{
            message: VAM.j('Ceiling price cannot be empty')
          },
          floatnumber:{
            message: VAM.j('Input correct number')
          },
          validnum2: {
            param: $('#floor_price'),
            message: VAM.j('The floor price cannot exceed the ceiling price')
          }
        },
        messageContainer:'ceiling_price_err'
      }
    };
    options = {
      submitOnSucceed: false,
      onvalidate: function(evt) {
        if (evt.resultList.length <= 0) {
          var materialVal = $('#upload_material').val(),
            $errorBox = $('#upload_material_err'),
            flag = true,
            msg = '';
          if (materialVal === '') {
            flag = false;
          };
          if (!flag) {
            msg = '<em class="checky-default-failure">' + VAM.j('Upload thumbnail cannot be empty') + '</em>';
            $errorBox.html(msg);
            return false;
          } else {
            $errorBox.html('');
          };

          $dataFrm.ajaxSubmit({
            beforeSubmit: function() {
              $submitBtn.button("loading");
            },
            success: function(data) {
              $submitBtn.button("reset");
              if (data.status === "success") {
                VamOpMsg.messager(data);
                window.location.href = "/app/app-list";
              } else {
                VamOpMsg.messager(data);
              }
            }
          });
        }
      }
    };
    formValidator.validate($dataFrm, dataFieldRule, options);
    dataValidator = formValidator.dataValidator;
    dataValidator.addRule("effectiveNumber", function(val, opt) {
      return !!(val && /^\d+(\.\d{1,2})?$/.test(val));
    });
    dataValidator.addRule("required", function(val, opt) {
      if (opt === "password") {
        return !!(val && !/^(?:\s\w|\u3000)+$/.test(val));
      } else {
        return !!(val && !/^(?:\s|\u3000)+$/.test(val));
      }
    });
    dataValidator.addRule('validnum1', function(val, opt) {
      if (opt.val() === '') {
        return true;
      }
      opt.trigger('blur');
      return true;
    });
    dataValidator.addRule('validnum2', function(val, opt) {
      if (opt.val() === '') {
        opt.trigger('blur');
        return true;
      }
      return parseInt(opt.val()) <= parseInt(val);
    });
  });

  // Init Creative Upload.
  $(function () {
    var $uploadMaterial = $('#upload-material'),
      $uploadMaterialModal = $('#upload-material-modal'),
      $uploadMaterialInput = $('#upload_material'),
      $uploadMaterialOperate = $('#upload-confirm-operate'),
      $creativePreviewWrap = $('.creative-preview-wrap'),
      $creativeMaterialDefault = $('#creative_material_default');
    $uploadMaterialModal.on('hidden.bs.modal', function (evt) {
      var $me = $(this);
      $('#progress .progress-bar').css('width','0%').text('0%');
      $('#files').find('tbody').html('');
    });

    $uploadMaterial.on('click', function (evt) {
      var $me = $(this);
      $uploadMaterialModal.modal('show');
    });
    
    $uploadMaterialOperate.on('click', function(evt) {
      var $me = $(this),
        $uploadMaterialErr = $('#upload_material_err'),
        materialId = $me.data('materialId'),
        prevewInfo = $me.data('materialInfo');
      evt.preventDefault();
      // console.log(materialId);
      // console.log(prevewInfo);
      if (materialId !== '') {
        $uploadMaterialInput.val(materialId);
        $uploadMaterialModal.modal('hide');
        $uploadMaterialErr.html('');
        // TODO: creative material preview.
        MaterialPreview.previewMultiple($('.creative-preview-wrap'), prevewInfo, materialId);
        $('#upload_material').trigger('blur');
        $('#creative-preview-details').children().remove();
      } else {
        $uploadMaterialInput.val('');
      };
    });
    $creativePreviewWrap.on('click', '.preview-close', function(evt) {
      var $me = $(this),
        $parent = $me.parent();
      evt.preventDefault();

      $parent.fadeOut(function() {
        $parent.remove();
        if ($creativePreviewWrap.find('.creative-preview').length === 0) {
          if ($creativeMaterialDefault.hasClass('hidden')) {
            $creativeMaterialDefault.removeClass('hidden');
          } else {
            $creativeMaterialDefault.show();
          };
          $("#upload_material").val("");
        };
      });
    });
  });

  // Upload Creative Material.
  $(function () {
    'use strict';
    var url = VAM.getVar('UPLOAD_MATERIAL_URL'),
        $fileUpload = $('#fileupload'),
        $progressBar = $('#progress .progress-bar'),
        $table = $('#files').find('table tbody');
    $fileUpload.fileupload({
        url: url,
        dataType: 'json',
        done: function (e, data) {
          if (data.result.status === 'success') {
            var materialData = data.result.data,
             list = materialData['table'],
             listStr = '';
            // console.log(materialData);
            VamOpMsg.messager(data.result);
            listStr = '<tr>'
                    + '<td>' + materialData.id + '</td>'
                    + '<td>' + list.name + '</td>'
                    + '<td>' + list.size + '</td>'
                    + '<td>' + list.date + '</td>'
                    + '<td>' + list.judgeInfo + '</td>'
                    + '<td>' + list.updater + '</td>'
                    + '</tr>';
            $table.append(listStr);
            $('#upload-confirm-operate').data('materialId', materialData.id).data('materialInfo', materialData['preview']);
          }else {
            VamOpMsg.messager(data.result);
            $('#upload-confirm-operate').data('materialId', '');
          };
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $progressBar.css('width','0%').text('0%');
            $progressBar.css(
                'width',
                progress + '%'
            ).text(progress + '%');
        }
    })
    .prop('disabled', !$.support.fileInput)
    .parent().addClass($.support.fileInput ? undefined : 'disabled');
  });
});
